const PREMADE_TEAMS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

const PREMADE_TEAM_COLORS = {
  A: { foregroundColor: 'orangered', borderColor: '#FFF3E8' },
  B: { foregroundColor: 'purple', borderColor: '#F5E8FF' },
  C: { foregroundColor: 'magenta', borderColor: '#FFE8F1' },
  D: { foregroundColor: 'pinkpurple', borderColor: '#FFE8FB' },
  E: { foregroundColor: 'cyan', borderColor: '#E8FFFB' },
}

export function GetPerTeams(preGames) {
  if (preGames.length <= 1) return;

  const groups = [];
  const visited = new Set();

  // 遍历每个玩家
  for (let i = 0; i < preGames.length; i++) {
    if (visited.has(i)) continue;

    const currentPerson = preGames[i];
    const currentGroup = [currentPerson.puuid];
    visited.add(i);

    // 检查后续玩家是否和当前玩家有共同游戏
    for (let j = i + 1; j < preGames.length; j++) {
      if (visited.has(j)) continue;

      const otherPerson = preGames[j];
      const sharedGameIds = new Set(
        currentPerson.games.filter((gameId) => otherPerson.games.includes(gameId)),
      );

      if (sharedGameIds.size >= 3) {
        currentGroup.push(otherPerson.puuid);
        visited.add(j);
      }
    }

    if (currentGroup.length > 1) {
      // 合并已存在的组
      let merged = false;
      for (let k = 0; k < groups.length; k++) {
        const existingGroup = groups[k];
        const intersection = currentGroup.filter((puuid) => existingGroup.includes(puuid));
        if (intersection.length > 0) {
          // 合并组
          groups[k] = [...new Set([...existingGroup, ...currentGroup])];
          merged = true;
          break;
        }
      }
      if (!merged) {
        groups.push(currentGroup);
      }
    }
  }

  return groups.map((group, index) => {
    const teamCode = PREMADE_TEAMS[index % PREMADE_TEAMS.length];
    const teamColor = PREMADE_TEAM_COLORS[teamCode] || { foregroundColor: '#000', borderColor: '#000' };
    return {
      code: teamCode,
      color: teamColor,
      puuids: group,
    };
  });
}
